<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-button type="primary" size="default" @click="addTrademark" :icon="Plus">添加</el-button>
        </template>
        <el-table :style="{marginBottom: '30px'}" :data="tabelData" border stripe>
            <el-table-column type="index" label="序号" align="center" width="80px"/>
            <el-table-column prop="tmName" label="品牌名称"></el-table-column>
            <el-table-column prop="logoUrl" label="品牌LOGO">
                <template #default="{row}">
                    <img :src="row.logoUrl" height="60" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{row}">
                    <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="deleteTrademark(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="limit"
            :page-sizes="[3, 5, 7, 9]"
            layout="prev, pager, next,sizes,total"
            :total="total" 
            :pager-count="5"
            >
        </el-pagination>
    </el-card>
    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id?'添加品牌':'修改品牌'">
    <el-form label-width="100px" :model="newTrademark" :rules="trademarkRules" ref="ruleFormRef">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input autocomplete="off" v-model="newTrademark.tmName"/>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
        <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrAddTrademark"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Trademark",
});
</script>

<script setup lang="ts">
    import {Plus,Edit,Delete} from '@element-plus/icons-vue'
    import type {reqTrademarkRecordsType,reqTrademarkItemType} from '@/api/trademark'
    import {requestTrademarkList,reqUpdateTrademark,reqAddTrademark,reqDeleteTrademark} from '@/api/trademark'
    import {ref,toRefs,onMounted,watch,reactive} from 'vue'
    import { ElMessage,ElMessageBox } from 'element-plus'
    import type { UploadProps,FormRules,FormInstance } from 'element-plus'

    //1.tabel数据
    const tabelData = ref<reqTrademarkRecordsType>([])

    //2.页码逻辑
    interface pageDateType {
        page:number,
        limit:number,
        total:number
    }
    const pageDate = ref<pageDateType>({
        page:1,
        limit:3,
        total:100
    })
    //解构
    const {page,limit,total} = toRefs(pageDate.value)

    //初始化获取
    onMounted(() => {
        getTrademarkList()
    })
    //3.获取品牌列表
    const getTrademarkList = async () => {
        const re = await requestTrademarkList({
            page:page.value,
            limit:limit.value
        })
        tabelData.value = re.records
        total.value = re.total
    }

    //点击页码逻辑
    watch([page,limit],() => {
        //重新获取列表
        getTrademarkList()
    })
    
    //控制弹窗显示与隐藏
    const dialogFormVisible = ref(false)
    const baseUrl = import.meta.env.VITE_API_URL
    const newTrademark = ref<reqTrademarkItemType>({
        tmName:'',
        logoUrl:'',
        id:0
    })

   //4.图片上传逻辑
    const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
    ) => {
    // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        newTrademark.value.logoUrl = response.data
    }

    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
    }

    //全局表单校验的ref实例，
    const ruleFormRef = ref<FormInstance>()

    //5.点击添加
    const addTrademark = () => {
        //清除残留校验规则
        ruleFormRef.value?.clearValidate()
        dialogFormVisible.value = true
        //清空以前的newTrademark，修改留下的数据双向绑定
        newTrademark.value = {
            tmName:'',
            logoUrl:'',
            id:0
        }
    }

    //6.点击修改
    const updateTrademark = (row:reqTrademarkItemType) => {
        //清除残留校验规则
        ruleFormRef.value?.clearValidate()
        dialogFormVisible.value = true
        newTrademark.value = {...row}
    }
    
    //7.添加或修改品牌列表
    const updateOrAddTrademark = async () => {
        try {
            //等待全局校验
            await ruleFormRef.value?.validate()
            dialogFormVisible.value = false
            try {
                if(newTrademark.value.id){
                    await reqUpdateTrademark(newTrademark.value)
                    ElMessage.success('修改成功')
                }else{
                    await reqAddTrademark(newTrademark.value)
                    ElMessage.success('添加成功')
                    page.value = 1
                }
                 //重新获取列表
                getTrademarkList()
            } catch (e) {
                ElMessage.error(newTrademark.value.id?'修改失败':'添加失败')
            }
        } catch (e) {
            e;
        }
       
    }

    //8.删除逻辑
    const deleteTrademark = async (id:number) => {
        ElMessageBox.confirm(
            '你真的要删除吗?',
            '警告！！！',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async () => {
            try {
                await reqDeleteTrademark(id)
                //重新获取列表
                getTrademarkList()
                ElMessage.success('删除成功')
            } catch (e) {
                ElMessage.error('删除失败')
            }
        }).catch(() => {
            ElMessage.info('点错了吗？')
        })
        
    }

    //自定义校验规则
    const validatePass = (rule: any, value: any, callback: any) => {
        if(value.length < 2 || value.length > 5){
            callback('长度必须是2-5')
        }else if(!value.trim()){
            callback('不能为空')
        }else{
            callback()
        }
    }
    //表单校验
    const trademarkRules = reactive<FormRules>({
        tmName:[
            { required: true, message: '必须填写品牌名称', trigger: 'blur' },
            { validator: validatePass, trigger: 'blur' },
        ],
        logoUrl:[
            { required: true, message: '必须上传图片', trigger: 'change' },
        ]
    })
</script>

<style scoped>
    .avatar-uploader .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    </style>
    
    <style>
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    
    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
    </style>